import fundebug from './fundebug'
const mockUserId = 0
const APP = getApp()

const GRAPHQL_ADDR = process.env.GRAPHQL_ADDR
/**
 * 请求
 * @param  {[String]} [url=GRAPHQL_ADDR] [description]
 * @param  {[Object]} data               [description]
 * @param  {[Object]} header             [description]
 * @param  {String} [method='POST'}]   [description]
 * @return {[Promise]}                    [description]
 */
export const req = async ({url = GRAPHQL_ADDR, data, header, method = 'POST', log = false, cache = true}) => {
  if (!url) {
    console.error('empty url!')
    return
  }
  if (log) {
    console.log(data)
  }
  let rs = await new Promise((resolve, reject) => {
    wx.request({
      url,
      data,
      header,
      method,
      success (res) {
        if (res.statusCode === 200) {
          resolve(res)
        } else {
          reject(res)
        }
      },
      fail (error) {
        reject(error)
      }
    })
  })
  if (log) {
    console.log(rs)
  }
  return rs
}

/**
 * [显示错误]
 * @param  {[Array]} errors [错误信息]
 * @return {[null]}        [null]
 */
const dealError = (errors) => {
  let msg = []
  errors.forEach(n => {
    msg.push(n.message)
  })
  msg = msg.join(',')

  if (msg.indexOf('ERR_NO_AUTH') >= 0) {
    wx.navigateTo({
      url: '/pages/auth/main'
    })
    return
  }
  wx.showToast({title: msg, icon: 'none'})
}

const gc = async ({ query, variables, operationName = '', log = false, cache = true, onLoading = (flag) => {} }) => {
  let token = getApp().globalData && getApp().globalData.token ? getApp().globalData.token : ''
  let authorization = ''
  const COS_ADDR = process.env.COS_ADDR
  if (process.env.NODE_ENV === 'development' && mockUserId) {
    authorization = mockUserId
  } else {
    authorization = 'Bearer ' + token
  }
  let header = {
    contentType: 'application/json',
    authorization
  }
  let res = null
  try {
    res = await req({
      header, data: {query, operationName, variables}, log, onLoading, cache
    })
  } catch (e) {
    fundebug.notifyError(e, {
      name: '请求错误',
      metaData: {
        header,
        query,
        variables
      }
    })
    throw e
  }

  if (res.data && res.data.errors && res.data.errors.length > 0) {
    dealError(res.data.errors)
  }

  return res.data
}

export default gc
